/**
 * Copyright (C) 2013-2014 the original author or authors.
 */
package com.foreveross.bsl.mam.rbac.web;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.inject.Inject;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.data.domain.Page;
import org.springframework.security.authentication.encoding.Md5PasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.foreveross.bsl.common.utils.enums.AccountStatus;
import com.foreveross.bsl.common.utils.exception.AppExcType;
import com.foreveross.bsl.common.utils.exception.ApplicationException;
import com.foreveross.bsl.common.utils.web.QueryFilter;
import com.foreveross.bsl.common.utils.web.QuerySpecs;
import com.foreveross.bsl.common.utils.web.model.PageMustache;
import com.foreveross.bsl.common.utils.web.model.QueryModelHelper;
import com.foreveross.bsl.common.utils.web.model.SelectBoxModel;
import com.foreveross.bsl.common.utils.web.model.SortInfoModel;
import com.foreveross.bsl.mam.rbac.application.RbacUserRoleApplication;
import com.foreveross.bsl.mam.rbac.application.RoleApplication;
import com.foreveross.bsl.mam.rbac.application.UserApplication;
import com.foreveross.bsl.mam.rbac.application.UserCategoryApplication;
import com.foreveross.bsl.mam.rbac.application.vo.RbacUserRoleVO;
import com.foreveross.bsl.mam.rbac.application.vo.RoleVO;
import com.foreveross.bsl.mam.rbac.application.vo.UserVO;
import com.foreveross.bsl.push.application.CheckinMgmtService;
import com.foreveross.bsl.push.application.PushService;
import com.foreveross.bsl.push.application.vo.DeviceCheckinVo;
import com.foreveross.bsl.push.application.vo.MessageParams;
import com.foreveross.bsl.push.application.vo.MessageVo;
import com.foreveross.bsl.push.application.vo.ReceiverTypeEnumVo;

/**
 * <BR>
 * [功能详细描述]
 * 
 * @author Amberlo
 * @version [bsl-web , 2013-6-24]
 */
@Controller
@RequestMapping("/rbac/user")
public class UserController extends RbacBaseController {
	private Logger log = Logger.getLogger(getClass());

	@Inject
	private UserApplication userApplication;
	@Inject
	private RoleApplication roleApplication;
	@Inject
	private RbacUserRoleApplication rbacApplication;
	@Inject
	private UserCategoryApplication userCategoryApplication;

	@Inject
	private PushService pushService;

	@Inject
	private CheckinMgmtService deviceCheckinService;

	/**
	 * ---------------------------------------------------基本方法------------------
	 * ---------------------------------------------
	 */
	@ResponseBody
	@RequestMapping("/add")
	public Map<String, Object> add(UserVO user) {
		Map<String, Object> result = new HashMap<String, Object>();

		user = saveUser(user);
		result.put("result", "success");
		return result;
	}

	/**
	 * @param user
	 */
	private UserVO saveUser(UserVO user) {
		if (user == null || StringUtils.isBlank(user.getUsername())) {
			throw new ApplicationException(AppExcType.BUS_TYPE,
					AppExcType.WEB_LAYER, AppExcType.MAM_MODUL, "001", "null.");
		}
		// 检测该用户是否已经注册
		UserVO u = userApplication.getUserByUserName(user.getUsername());
		if (u != null) {
			throw new ApplicationException(AppExcType.BUS_TYPE,
					AppExcType.WEB_LAYER, AppExcType.MAM_MODUL, "002",
					"registered");
		}
		// user.setUserType("终端用户");
		user = userApplication.saveEntity(user);
		return user;
	}

	@ResponseBody
	@RequestMapping("/delete")
	public Map<String, Object> delete(String[] ids) {
		Map<String, Object> result = new HashMap<String, Object>();
		if (ids != null) {
			for (String id : ids) {
				userApplication.deleteEntity(id);
				rbacApplication.deleteByUserId(id);
			}
		}
		result.put("result", "success");
		return result;
	}

	@ResponseBody
	@RequestMapping("/get")
	public Map<String, Object> get(@RequestParam String id) {
		Map<String, Object> result = new HashMap<String, Object>();
		UserVO user = userApplication.getEntity(id);
		result.put("data", user);
		return result;
	}

	@ResponseBody
	@RequestMapping("/all")
	public List<UserVO> findAllUser() {
		List<UserVO> users = userApplication.findAll();
		try {
			for (UserVO user : users) {
				List<RoleVO> roles = rbacApplication.getRolesByUserID(user
						.getId());
				if (roles != null) {
					user.setRoles(roles);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return users;
	}

	/**
	 * 显示界面
	 * 
	 * @param model
	 * @return
	 */
	@RequestMapping("/user-view")
	public String listView(
			Model model,
			@RequestParam(value = "page", defaultValue = "1") int pageNumber,
			@RequestParam(value = "page.size", defaultValue = "10") int pageSize,
			HttpServletRequest request) {

		String queryUrl = "/rbac/user/user-view";
		QueryModelHelper queryHelper = new QueryModelHelper(queryUrl,
				makeQueryFields(), makeSortInfo());
		QuerySpecs querySpecs = queryHelper.populateQueryModel(model, request);
		Page<UserVO> userList = userApplication.findUsersBySpec(pageNumber,
				pageSize, querySpecs);

		// Pageable pageable = new PageRequest(pageNumber-1, pageSize);
		// Page<UserVO> userList = userApplication.findByPageable(pageable);
		// add by lizhfeng 下拉菜单选中内容应该与搜索相对应
		QueryFilter firstFilter = querySpecs.getFirstFilter();
		if (firstFilter.getFieldName() != null) {
			model.addAttribute(
					"fieldName",
					"q_" + firstFilter.getOperator().name() + "_"
							+ firstFilter.getFieldName());
		}
		model.addAttribute("page", new PageMustache(userList, 10));
		model.addAttribute("userTypeList", userCategoryApplication.findAll());
		model.addAttribute("roleList", roleApplication.findAll());
		model.addAttribute("list", userList);

		return "rbac/rbac-user";
	}

	private final SortInfoModel makeSortInfo() {
		SortInfoModel sim = new SortInfoModel();

		sim.setSortEntry("username", "用户名", true);
		sim.setSortEntry("name", "昵称", true);
		// sim.setSortEntry("sex", "性别", true);
		return sim;
	}

	/**
	 * ----------------------------------------业务功能----------------------------
	 * ----------------
	 */

	/**
	 * 锁定用户
	 * 
	 * @param id
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/setUserStatus")
	public Map<String, Object> setUserStatus(String id, String status) {
		Map<String, Object> result = new HashMap<String, Object>();

		UserVO user = userApplication.getEntity(id);
		AccountStatus as = AccountStatus.getByCode(status);
		if (as == null) {
			throw new ApplicationException(AppExcType.BUS_TYPE,
					AppExcType.WEB_LAYER, AppExcType.MAM_MODUL, "003",
					"the status code is not exist.");
		}
		user.setStatus(as.getValue());
		userApplication.updateEntity(user);
		result.put("result", "success");
		return result;
	}

	// /**
	// * 锁定用户群
	// * @param ids
	// * @return
	// */
	// @ResponseBody
	// @RequestMapping("/lockUsers")
	// public String lockUsers(String[] ids) {
	// for(String id:ids){
	// UserVO user = userApplication.getEntity(id);
	// if(user!=null){
	// user.setStatus("锁定");
	// userApplication.updateEntity(user);
	// }
	// }
	// return "success";
	// }

	/**
	 * 重置密码
	 * 
	 * @param id
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/resetPassword")
	public String resetPassword(String id) {
		UserVO user = userApplication.getEntity(id);
		if (user != null) {
			user.setPassword("000000");
			Md5PasswordEncoder md = new Md5PasswordEncoder();
			String encodePassword = md.encodePassword(user.getPassword(),
					user.getUsername());
			user.setPassword(encodePassword);
			userApplication.updateEntity(user);
		}
		return "success";
	}

	/**
	 * 修改密码
	 * 
	 * @param id
	 * @param password
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/setPassword")
	public String setPassword(String id, String password) {
		// Map<String, String> result = new HashMap<String, String>();
		UserVO user = userApplication.getEntity(id);
		if (user != null) {
			user.setPassword(password);
			Md5PasswordEncoder md = new Md5PasswordEncoder();
			String encodePassword = md.encodePassword(user.getPassword(),
					user.getUsername());
			user.setPassword(encodePassword);
			userApplication.updateEntity(user);
		}
		// result.put("result", "success");
		return "success";
	}

	/**
	 * 通过用户id查找相关的所有角色
	 * 
	 * @param userId
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/getUserAndRoles")
	public UserVO getUserAndRoles(String userId) {
		UserVO user = userApplication.getEntity(userId);
		if (user != null) {
			List<RoleVO> roles = rbacApplication.getRolesByUserID(userId);
			user.setRoles(roles);
		}
		return user;
	}

	/**
	 * 提交用户信息
	 * 
	 * @param username
	 * @param password
	 * @param roleIDs
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/addUserAndRoles")
	public String addUserAndRoles(UserVO user) {
		try {
			user = saveUser(user);
		} catch (ApplicationException e) {
			e.printStackTrace();
			return e.getMessage();
		}
		// if (user.getRoles() != null && user.getRoles().size()!=0)
		if (user.getRoleIds() != null && user.getRoleIds().length != 0) {
			// List<String> roles = new ArrayList<String>();
			// for(RoleVO r:user.getRoles()){
			// roles.add(r.getId());
			// }
			rbacApplication.addRolesIDToUser(user.getId(),
					Arrays.asList(user.getRoleIds()));
			// rbacApplication.addRolesIDToUser(user.getId(), roles);
		}
		return "success";
	}

	/**
	 * 编辑用户信息
	 * 
	 * @param user
	 * @return
	 */
	@RequestMapping("/editUser")
	public String editUser(UserVO user) {
		List<RoleVO> orgRoleVList = this.rbacApplication.getRolesByUserID(user
				.getId());

		List<String> destRoleVList = new ArrayList<String>();
		this.rbacApplication.deleteByUserId(user.getId());
		if (user.getRoleIds() != null) {
			for (String roleId : user.getRoleIds()) {
				if (roleId != null) {
					String result = addRole(user.getId(), roleId);
					if ("success".equals(result)) {
						destRoleVList.add(roleId);
					}
				}
			}
		}
		if ((user.getPassword() == null) || (user.getPassword().equals(""))) {
			user.setPassword(this.userApplication.getEntity(user.getId())
					.getPassword());
		} else {
			Md5PasswordEncoder md = new Md5PasswordEncoder();
			String encodePassword = md.encodePassword(user.getPassword(),
					user.getUsername());

			user.setPassword(encodePassword);
		}
		this.userApplication.updateEntity(user);
		try {
			pushMessage(orgRoleVList, destRoleVList, user.getUsername());
		} catch (Exception e) {
		}
		return "redirect:user-view";
	}

	/**
	 * 用户添加单个角色
	 * 
	 * @param userID
	 * @param roleId
	 * @return
	 */
	public String addRole(String userID, String roleId) {
		RbacUserRoleVO relations = new RbacUserRoleVO();
		if (roleApplication.getEntity(roleId) == null) {
			System.out.println("role does not exist,continue it");
			return "failed";
		}
		relations.setRole_ID(roleId);
		relations.setUser_ID(userID);
		rbacApplication.saveEntity(relations);
		System.out.println("rbac save success");
		return "success";
	}

	private final SelectBoxModel makeQueryFields() {
		SelectBoxModel sbm = new SelectBoxModel();
		sbm.addOption("LIKE_username", "用户名");
		sbm.addOption("LIKE_name", "昵称");
		// sbm.addOption("EQ_sex", "性别");
		return sbm;
	}

	/**
	 * 用户导入
	 * 
	 * @param file
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/importUser")
	public Map<String, Object> importUser(@RequestParam MultipartFile file) {
		Map<String, Object> validateResult = validateFile(file);
		if ("false".equals((String) validateResult.get("result"))) {
			return validateResult;
		}

		return processFile(file);
	}

	@SuppressWarnings("unchecked")
	private Map<String, Object> processFile(MultipartFile file) {
		Map<String, Object> _result = new HashMap<String, Object>();
		List<String> colNames = new ArrayList<String>();
		colNames.add("用户名");
		colNames.add("用户昵称");
		colNames.add("邮箱");
		colNames.add("角色");
		colNames.add("性别");
		colNames.add("联系电话");
		String fileName = file.getOriginalFilename();
		String ext = fileName.substring(fileName.lastIndexOf(".") + 1)
				.toUpperCase();
		InputStream in = null;
		try {
			in = file.getInputStream();
			// Map<Integer, Map<String, String>> map = ext.equals("XLSX") ?
			// readExcelContent(in) : readExcelContent03(in);
			Object[] _res = ext.equals("XLSX") ? readExcelContent(in)
					: readExcelContent03(in);
			Map<Integer, Map<String, String>> map = (Map<Integer, Map<String, String>>) _res[0];
			if (_res.length < 2 || _res[1] == null) {
				_result.put("result", "false");
				_result.put("msg", "EXCEL文件内容格式不对");
				return _result;
			}
			Map<Integer, String> colMap = (Map<Integer, String>) _res[1];
			if (colMap != null && colMap.keySet().size() > 0) {
				for (Integer k : colMap.keySet()) {
					if (!colNames.contains(colMap.get(k))) {
						_result.put("result", "false");
						_result.put("msg", "EXCEL文件内容格式不对");
						return _result;
					}
				}
			}

			Set<String> newRoleSet = null;
			String upRoles[] = null;
			List<UserVO> editUser = new ArrayList<UserVO>();
			List<UserVO> addUser = new ArrayList<UserVO>();
			String msgPre = "第 {0}行:";
			for (int i = 1; i <= map.size(); i++) {
				Map<String, String> rowConent = map.get(i);
				String users[] = new String[rowConent.size()];
				for (String key : rowConent.keySet()) {
					if (key.equals("用户名")) {
						users[0] = rowConent.get(key);
					}
					if (key.equals("用户昵称")) {
						users[1] = rowConent.get(key);
					}
					if (key.equals("邮箱")) {
						users[2] = rowConent.get(key);
					}
					if (key.equals("角色")) {
						users[3] = rowConent.get(key);
					}
					if (key.equals("性别")) {
						users[4] = rowConent.get(key);
					}
					if (key.equals("联系电话")) {
						users[5] = rowConent.get(key);
					}
				}
				if (StringUtils.isEmpty(users[0])
						&& StringUtils.isEmpty(users[1])
						&& StringUtils.isEmpty(users[2])
						&& StringUtils.isEmpty(users[3])
						&& StringUtils.isEmpty(users[4])
						&& StringUtils.isEmpty(users[5])) {
					continue;
				}
				if (StringUtils.isEmpty(users[0])) {
					_result.put("result", "false");
					_result.put("msg", msgPre.replace("{0}", (i + 1) + "")
							+ "用户名为空");
					return _result;
				}
				if (StringUtils.isEmpty(users[4])) {
					_result.put("result", "false");
					_result.put("msg", msgPre.replace("{0}", (i + 1) + "")
							+ "性别为空");
					return _result;
				}
				if (!"male".equals(users[4]) && !"female".equals(users[4])) {
					_result.put("result", "false");
					_result.put("msg", msgPre.replace("{0}", (i + 1) + "")
							+ "性别输入有误");
					return _result;
				}
				if (!emailCheck(users[2])) {
					_result.put("result", "false");
					_result.put("msg", msgPre.replace("{0}", (i + 1) + "")
							+ "邮箱格式输入有误");
					return _result;
				}
				UserVO user = new UserVO();

				user.setUsername(users[0]);
				user.setName(users[1]);
				user.setAddress(users[2]);
				user.setTelephone(users[5]);
				String newSex = "";
				if (users[4].equals("male")) {
					newSex = "M";
					user.setSex("M");
				} else if (users[4].equals("female")) {
					newSex = "F";
					user.setSex("F");
				}
				user.setPassword("000000");
				List<RoleVO> list = new ArrayList<RoleVO>();
				newRoleSet = new HashSet<String>();
				if (!StringUtils.isEmpty(users[3])) {
					upRoles = users[3].split(",");
					if (upRoles != null) {
						for (String rol : upRoles) {
							newRoleSet.add(rol);
						}
					}
				}
				UserVO exitUser = userApplication.getUserByUserName(users[0]);
				if (exitUser != null) {
					exitUser.setRoles(new ArrayList<RoleVO>());
					exitUser.setName(users[1]);
					exitUser.setAddress(users[2]);
					exitUser.setTelephone(users[5]);
					exitUser.setSex(newSex);
					RoleVO rl = null;
					for (String newRole : newRoleSet) {
						rl = roleApplication.getRoleByName(newRole);
						if (rl != null) {
							exitUser.getRoles().add(rl);
						}
					}

					editUser.add(exitUser);
				} else {
					RoleVO role = null;
					for (String newRole : newRoleSet) {
						role = roleApplication.getRoleByName(newRole);
						if (role != null) {
							list.add(role);
						}
					}

					user.setRoles(list);
					addUser.add(user);
				}

			}

			if (addUser.isEmpty() && editUser.isEmpty()) {
				_result.put("result", "false");
				_result.put("msg", "EXCEL文件内容为空");
				return _result;
			}
			for (UserVO user1 : addUser) {
				user1 = userApplication.saveEntity(user1);
				if (user1.getRoles() != null && !user1.getRoles().isEmpty()) {
					List<String> roleIds = new ArrayList<String>();
					for (RoleVO rol : user1.getRoles()) {
						roleIds.add(rol.getId());
					}
					rbacApplication.addRolesIDToUser(user1.getId(), roleIds);
				}
			}

			for (UserVO user2 : editUser) {
				userApplication.updateEntity(user2);
				rbacApplication.deleteByUserId(user2.getId());
				if (!user2.getRoles().isEmpty()) {
					List<String> roleIds = new ArrayList<String>();
					for (RoleVO rol : user2.getRoles()) {
						roleIds.add(rol.getId());
					}
					rbacApplication.addRolesIDToUser(user2.getId(), roleIds);
				}
			}
			_result.put("result", "true");
			_result.put("msg", "导入成功");
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				if (in != null)
					in.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}

		return _result;
	}

	private boolean emailCheck(String email) {
		boolean tag = true;
		if (StringUtils.isEmpty(email)) {
			return tag;
		}
		final String pattern1 = "^([a-z0-9A-Z]+[-|\\.]?)+[a-z0-9A-Z]@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-zA-Z]{2,}$";
		final Pattern pattern = Pattern.compile(pattern1);
		final Matcher mat = pattern.matcher(email);
		if (!mat.find()) {
			tag = false;
		}
		return tag;
	}

	private Object[] readExcelContent03(InputStream in) {
		Object[] _result = new Object[2];
		Map<Integer, Map<String, String>> contents = new LinkedHashMap<Integer, Map<String, String>>();
		_result[0] = contents;
		String str = "";
		try {
			HSSFWorkbook wb = new HSSFWorkbook(in);
			HSSFSheet sheet = wb.getSheetAt(0);
			int rowNum = sheet.getLastRowNum();
			Row row = sheet.getRow(0);
			if (row == null) {
				return _result;
			}
			int colNum = row.getPhysicalNumberOfCells();
			Map<Integer, String> map = new HashMap<Integer, String>();
			_result[1] = map;
			for (int i = 0; i <= rowNum; i++) {

				Map<String, String> rowMap = new HashMap<String, String>();
				if (i == 0) {
					row = sheet.getRow(i);
					int j = 0;
					while (j < colNum) {
						str = getStringCellValue03(row.getCell((short) j))
								.trim();
						map.put(j, str);

						j++;
					}
				} else {
					row = sheet.getRow(i);
					int j = 0;
					while (j < colNum) {
						rowMap.put(map.get(j),
								getStringCellValue03(row.getCell((short) j))
										.trim());
						// str += getStringCellValue(row.getCell((short)
						// j)).trim() + "htky";
						j++;
					}
					contents.put(i, rowMap);
				}
				str = "";

			}
		} catch (IOException e) {
			e.printStackTrace();
		}

		return _result;
	}

	private Object[] readExcelContent(InputStream in) {
		Object[] _result = new Object[2];
		Map<Integer, Map<String, String>> contents = new LinkedHashMap<Integer, Map<String, String>>();
		_result[0] = contents;
		String str = "";
		try {
			XSSFWorkbook wb = new XSSFWorkbook(in);
			// HSSFWorkbook wb = new HSSFWorkbook(input);
			XSSFSheet sheet = wb.getSheetAt(0);
			// 得到总行数
			int rowNum = sheet.getLastRowNum();
			XSSFRow row = sheet.getRow(0);
			if (row == null) {
				return _result;
			}
			int colNum = row.getPhysicalNumberOfCells();
			Map<Integer, String> map = new HashMap<Integer, String>();
			_result[1] = map;
			// 正文内容应该从第二行开始,第一行为表头的标题,上次就中招了
			for (int i = 0; i <= rowNum; i++) {

				Map<String, String> rowMap = new HashMap<String, String>();
				if (i == 0) {
					row = sheet.getRow(i);
					int j = 0;
					while (j < colNum) {
						str = getStringCellValue(row.getCell((short) j)).trim();
						map.put(j, str);

						j++;
					}
				} else {
					row = sheet.getRow(i);
					int j = 0;
					while (j < colNum) {
						rowMap.put(map.get(j),
								getStringCellValue(row.getCell((short) j))
										.trim());
						// str += getStringCellValue(row.getCell((short)
						// j)).trim() + "htky";
						j++;
					}
					contents.put(i, rowMap);
				}
				str = "";

			}
		} catch (IOException e) {
			e.printStackTrace();
		}

		return _result;
	}

	private Map<String, Object> validateFile(MultipartFile file) {
		Map<String, Object> msgMap = new HashMap<String, Object>();
		if (file == null) {
			msgMap.put("result", "false");
			msgMap.put("msg", "没有上传文件！");
			return msgMap;
		}
		String fileName = file.getOriginalFilename();
		String nameExt = fileName.substring(fileName.lastIndexOf(".") + 1)
				.toUpperCase();
		if (!nameExt.equals("XLSX") && !nameExt.equals("XLS")) {
			msgMap.put("result", "false");
			msgMap.put("msg", "文件格式不正确！");
			return msgMap;
		}

		msgMap.put("result", "true");
		return msgMap;
	}

	/**
	 * 获取单元格数据内容为字符串类型的数据
	 * 
	 * @param Cell
	 *            Excel单元格
	 * @return String 单元格数据内容
	 */
	private String getStringCellValue03(Cell cell) {
		String strCell = "   ";
		if (cell == null) {
			return strCell;
		}
		switch (cell.getCellType()) {
		case Cell.CELL_TYPE_STRING:
			strCell = cell.getStringCellValue();
			break;
		case Cell.CELL_TYPE_NUMERIC:
			strCell = String.valueOf(cell.getNumericCellValue());
			break;
		case Cell.CELL_TYPE_BOOLEAN:
			strCell = String.valueOf(cell.getBooleanCellValue());
			break;
		case Cell.CELL_TYPE_BLANK:
			strCell = "";
			break;
		default:
			strCell = "";
			break;
		}
		if (strCell.equals("") || strCell == null) {
			return "";
		}
		return strCell;
	}

	/**
	 * 获取单元格数据内容为字符串类型的数据
	 * 
	 * @param xssfCell
	 *            Excel单元格
	 * @return String 单元格数据内容
	 */
	private String getStringCellValue(XSSFCell xssfCell) {
		String strCell = "   ";
		if (xssfCell == null) {
			return strCell;
		}
		switch (xssfCell.getCellType()) {
		case HSSFCell.CELL_TYPE_STRING:
			strCell = xssfCell.getStringCellValue();
			break;
		case HSSFCell.CELL_TYPE_NUMERIC:
			strCell = String.valueOf(xssfCell.getNumericCellValue());
			break;
		case HSSFCell.CELL_TYPE_BOOLEAN:
			strCell = String.valueOf(xssfCell.getBooleanCellValue());
			break;
		case HSSFCell.CELL_TYPE_BLANK:
			strCell = "";
			break;
		default:
			strCell = "";
			break;
		}
		if (strCell.equals("") || strCell == null) {
			return "";
		}
		return strCell;
	}

	private void pushMessage(List<RoleVO> orgList, List<String> destList,
			String userName) {
		Map<String, String> map = new HashMap<String, String>();
		if ((orgList != null) && (orgList.size() > 0)) {
			for (RoleVO vo : orgList) {
				map.put(vo.getId(), vo.getId());
			}
		}

		List<QueryFilter> filters = new ArrayList<QueryFilter>();
		QueryFilter appidfilter = new QueryFilter("alias",
				QueryFilter.Operator.EQ, userName);

		filters.add(appidfilter);
		QuerySpecs querySpecs = new QuerySpecs(filters);
		Page<DeviceCheckinVo> page = this.deviceCheckinService.findPageBy(1,
				10, querySpecs);
		if ((page != null) && (page.getSize() > 0)) {
			String appKey = ((DeviceCheckinVo) page.getContent().get(0))
					.getAppId();
			MessageParams msgParams = new MessageParams();
			msgParams.setReceiverType(ReceiverTypeEnumVo.ALIAS);
			msgParams.setReceiverValue(userName);
			msgParams.setAppId(appKey);
			MessageVo messageVo = new MessageVo();
			messageVo.setMessageType(MessageVo.MessageTypeEnum.SECURITY);
			messageVo.putExtra("securityKey", "roles");//角色变更
			messageVo.setTitle("安全策略变更");
			msgParams.setMessage(messageVo);
			if ((destList != null) && (destList.size() > 0)) {
				boolean flag = false;

				for (String destRoleId : destList) {
					if (!map.containsKey(destRoleId)) {
						flag = true;
						break;
					}
				}
				if (flag) {
					String pushRequestId = this.pushService
							.submitMessage(msgParams);

					this.log.info("[submitMessage]用户角色变更，推送消息返回结果："
							+ pushRequestId);
				} else if ((map.size() > 0) && (destList.size() != map.size())) {
					String pushRequestId = this.pushService
							.submitMessage(msgParams);

					this.log.info("[submitMessage]用户角色变更，推送消息返回结果："
							+ pushRequestId);
				}
			} else {
				String pushRequestId = this.pushService
						.submitMessage(msgParams);

				this.log.info("[submitMessage]用户角色变更，推送消息返回结果：" + pushRequestId);
			}
		}
	}

}
